import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import LoggedInLayout from '@/layouts/LoggedInLayout.vue'
import Home from '@/views/Home.vue'
import MenuView from '@/views/MenuView.vue'
import CartView from '@/views/CartView.vue'
import CheckoutView from '@/views/CheckoutView.vue'
import AdminUsers from '@/views/AdminUsers.vue'
import NotFound from '@/views/NotFound.vue'

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: () => import('@/components/Register.vue') },
  { path: '/reset-password', component: () => import('@/components/ResetPassword.vue') },

  // 主体路由
  {
    path: '/',
    component: LoggedInLayout,
    meta: { requiresAuth: true },
    children: [
      { path: '', name: 'home', component: Home },
      { path: 'menu', name: 'menu', component: MenuView },
      { path: 'cart', name: 'cart', component: CartView },
      { path: 'checkout', name: 'checkout', component: CheckoutView }
    ]
  },

  // 管理员路由（保持不变）
  {
    path: '/admin',
    component: LoggedInLayout,
    meta: { requiresAuth: true, roles: ['ADMIN'] },
    children: [
      { path: '', redirect: '/admin/users' },
      { path: 'users', component: AdminUsers },
      { path: 'orders', component: () => import('@/views/merchant/OrderList.vue') },
      { path: 'reviews', component: () => import('@/views/admin/ReviewList.vue') }
    ]
  },

  // 商家路由
  {
    path: '/merchant',
    component: LoggedInLayout,
    meta: { requiresAuth: true, roles: ['MERCHANT'] },
    children: [
      { path: '', redirect: '/merchant/dishes' },
      { path: 'dishes', component: () => import('@/views/merchant/DishList.vue') },
      { path: 'dishes/add', component: () => import('@/views/merchant/DishForm.vue') },
      { path: 'dishes/edit/:id', component: () => import('@/views/merchant/DishForm.vue') },
      { path: 'orders', component: () => import('@/views/merchant/OrderList.vue') }
    ]
  },

  { path: '/:pathMatch(.*)*', component: NotFound }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 权限守卫
router.beforeEach(async (to, from, next) => {
  const { useUserStore } = await import('@/stores/user')
  const store = useUserStore()
  await store.refreshToken()

  // 如果需要认证且没有token
  if (to.meta.requiresAuth && !store.token) return next('/login')

  // 如果有token但没有获取用户名（这意味着获取用户信息）
  if (store.token && !store.username) {
    const ok = await store.fetchUser()
    if (!ok) return next('/login')
  }

  // 检查角色权限
  if (to.meta.roles && !to.meta.roles.some(r => store.permissions.includes(r))) {
    alert('无权限访问')
    return next('/')
  }

  next()
})


export default router
